package com.share.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class demo3_fileDownload extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String path = getServletContext().getRealPath("/WEB-INF/jpg/hand.jpg");
        String fileName = path.substring(path.lastIndexOf("\\") + 1);
        System.out.println("前：" + fileName);
        //使用特定的编码方案将字符串转换为application/x-www-form-urlencoded格式。 此方法使用提供的编码方案来获取不安全字符的字节。
        fileName = URLEncoder.encode(fileName, "utf-8");
        System.out.println("后：" + fileName);

        //告知浏览器下载文件
        resp.setHeader("content-disposition", "attachment;filename=" + fileName);

        //告知浏览器content-tppe
        resp.setHeader("content-type", "image/jpeg");

        //copy
        FileInputStream in = new FileInputStream(path);
        ServletOutputStream out = resp.getOutputStream();
        byte[] arr = new byte[1024*8];
        int len;
        while((len = in.read(arr)) != -1) {
            out.write(arr, 0, len);
        }

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
